<?php
namespace base\pay;
use think\facade\Cache;

require root_path().'/vendor/alipay/aop/AopClient.php';
require root_path().'/vendor/alipay/aop/request/AlipayTradeAppPayRequest.php';
require root_path().'/vendor/alipay/aop/request/AlipayTradeWapPayRequest.php';
require root_path().'/vendor/alipay/aop/request/AlipayTradeRefundRequest.php';
 
//---------------------------------
//---------支付宝api----------------
//---------------------------------
class AliPayApi {

	var $aop;
	
	//初始配置
	public function __construct()
	{
	    //zhifubao
	    $config = env('system_base_config_alipay'); 
        if(!$config){
           throw new \think\Exception( '请先配置支付宝应用信息' );
        }
        $this->aop    =    new \AopClient();
        $this->aop->appId                        = $config['appid'];
        $this->aop->rsaPrivateKey            = $config['rsa_private_key'];//私有密钥
        $this->aop->alipayrsaPublicKey    = $config['rsa_public_key'];//共有密钥
        $this->aop->gatewayUrl               = $config['alipay_gateway_url'];
        $this->aop->format                      = "json";
        $this->aop->charset                      = "utf-8";
        $this->aop->signType                   = "RSA2";
	}

    
	/**
     * 创建APP支付订单
     *
     * @param string $body 对一笔交易的具体描述信息。
     * @param string $subject 商品的标题/交易标题/订单标题/订单关键字等。
     * @param string $order_sn 商户网站唯一订单号
     * @return array 返回订单信息
     */
    public  function tradeAppPay($order_sn,$total_amount,$is_page=false,$body="",$subject="")
    {
        if($is_page){
        	$request = new \AlipayTradeAppPayRequest();
        }else{
        	$request = new \AlipayTradeWapPayRequest();
        }
		
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = [
            'body'                =>   $body ?: '商品',
            'subject'            =>    $subject ?: '纸巾定制',
            'out_trade_no'        =>    $order_sn,
            'timeout_express'    =>    '10d', //失效时间为 3小时
            'total_amount'        =>    $total_amount,//价格
            'product_code'        =>    'QUICK_WAP_PAY',
        ];
        //商户外网可以访问的异步地址 (异步回掉地址，根据自己需求写)
        $config = env('system_base_config_alipay'); 
        $request->setNotifyUrl($config['notify_url']);
        $request->setBizContent(json_encode($bizcontent));
        //这里和普通的接口调用不同，使用的是sdkExecute
        if($is_page){
        	$response = $this->aop->sdkExecute($request);
        }else{
        	$response = $this->aop->pageExecute($request);
        }
		
		Cache('AliPayApi_orderNo_'.$order_sn,$response);
        
        return env('APP_HOST').'/system/payment/alipayPay.html?order_no='.$order_sn;
    }
	
	/**
     * 异步通知验签
     *
     * @param string $params 参数
     * @param string $signType 签名类型：默认RSA
     * @return bool 是否通过
     */
    public  function rsaCheck($params, $signType)
    {
        return $this->aop->rsaCheckV1($params, NULL, $signType);
    }
	
	/**
     * 根据订单号退款
     */
    public  function payOrderRefund($orderNo,$price)
    {
		$request = new \AlipayTradeRefundRequest();
		$bizcontent = [
            'out_trade_no'     => $orderNo,
            'refund_amount' => strval($price),
        ];
		$request->setBizContent(json_encode($bizcontent));
		$result = (new self)->aop->execute($request); 
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->code;
		$resultMsg = $result->$responseNode->sub_msg;
		if(!empty($resultCode) && $resultCode == 10000){
			return true;
		}else{
			throw new \think\Exception('退款失败: '. $resultMsg);
		}
    }
}


